
"use client";

import { SiteFooter } from '@/components/site-footer';
import { SectionHeader } from '@/components/section-header';
import { ToolCard } from '@/components/tool-card';
import { CategoryModal } from '@/components/CategoryModal';
import { useMemo, useState } from 'react';
import type { Category } from '@/types/category';
import type { Content } from '@/types/content';

interface GroupedContents {
  [key: string]: Content[];
}

type ClientProps = {
  sysCode: string;
  nav: { id: string; name: string; categories: Category[] } | null;
  groupedContents: GroupedContents;
};

export default function NavCategoryContentClient({ sysCode, nav, groupedContents }: ClientProps) {
  const [modalOpen, setModalOpen] = useState(false);
  const [selectedCategory, setSelectedCategory] = useState<Category | null>(null);

  const modalContents = useMemo(
    () => (selectedCategory ? groupedContents[selectedCategory.id] || [] : []),
    [selectedCategory, groupedContents]
  );

  const handleMoreClick = (category: Category) => {
    setSelectedCategory(category);
    setModalOpen(true);
  };

  return (
    <main className="flex-1 overflow-y-auto flex flex-col">
      <div className="container mx-auto px-4 py-6 max-w-7xl flex-1">
        {nav?.categories?.map((category) => (
          <div key={category.id} id={category.id} className="scroll-mt-20 mb-8">
            <SectionHeader title={category.name} onMoreClick={() => handleMoreClick(category)} />
            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mt-4">
              {groupedContents[category.id]?.slice(0, 8).map((content) => (
                <ToolCard
                  key={content.id}
                  id={content.id}
                  name={content.title}
                  description={content.content}
                  icon={content.cover?.url || ''}
                  viewCount={content.viewCount}
                  favoritesCount={content.favoritesCount}
                />
              ))}
            </div>
          </div>
        ))}
      </div>
      <SiteFooter />

      <CategoryModal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        category={selectedCategory}
        contents={modalContents}
      />
    </main>
  );
}